<script setup>
import productApi from "@/api/product.js";
import categoryApi from "@/api/catetory.js";
import WangEditor from "@/components/WangEditor.vue";
import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {
  Delete,
  Edit,
  Upload,
  Download,
  Plus
} from '@element-plus/icons-vue'
import router from "@/router/index.js";
//数据表格
const list = ref([])
const total = ref(0)
//分页信息和搜索条件
const productQuery = ref({
  name: '',
  page: 1,
  limit: 10
})
const dateTimeRange = ref([])

/*productApi.list(productQuery.value).then(result => {
    list.value = result.data.records
    total.value = result.data.total
})*/

const loadData = () => {
  productApi.list(productQuery.value).then(result => {
    if (result.code == 0) {
      list.value = result.data.records
      total.value = result.data.total
    }
  })
}

loadData()

const onSearch = () => {
  productQuery.value.page = 1
  productQuery.value.beginUpdateTime = null
  productQuery.value.endUpdateTime = null
  productQuery.value.topCategoryId =null
  if (dateTimeRange.value && dateTimeRange.value.length == 2) {
    productQuery.value.beginUpdateTime = dateTimeRange.value[0]
    productQuery.value.endUpdateTime = dateTimeRange.value[1]
  }
  productQuery.value.topCategoryId = topCategory.value || null

  // 二级分类（没选时设为 null，而不是空字符串）
  if (!productQuery.value.categoryId) {
    productQuery.value.categoryId = null
  }
  loadData()
}

const reset = () => {
  productQuery.value.name = ''
  productQuery.value.phone = ''
  dateTimeRange.value = []
  topCategory.value = ''
  secondCategoryList.value = []
  productQuery.value.categoryId = ''
}

//根据id删除
const deleteById = (id) => {
  ElMessageBox.confirm(
      '您确认要删除么?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    productApi.deleteById(id).then(result => {
      if (result.code == 0) {
        ElMessage.success(result.msg)
        loadData()
      } else {
        ElMessage.error(result.msg)
      }
    })
  })
}

//批量删除
const ids = ref([])
const handleSelectionChange = (rows) => {
  console.log('多选', rows)
  ids.value = rows.map(function (row) {
    return row.id;
  })
  console.log(ids.value)
}

const deleteAll = () => {
  ElMessageBox.confirm(
      '您确认要删除么?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    productApi.deleteAll(ids.value).then(result => {
      if (result.code == 0) {
        ElMessage.success(result.msg)
        loadData()
      } else {
        ElMessage.error(result.msg)
      }
    })
  })
}

//添加、编辑
const dialogFormVisible = ref(false)
const product = ref({})
const showAddDialog = () => {
  product.value = {}
  dialogFormVisible.value = true
  secondCategoryList.value = []
  topCategory.value = ''
}

/*const showUpdateDialog = (id) => {
  dialogFormVisible.value = true
  product.value = {}
  productApi.selectById(id).then(result => {
    if (result.code == 0) {
      product.value = result.data

      const second = secondCategoryList.value.find(c => c.name === product.value.secondCategoryName)
      if (second) {
        product.value.categoryId = second.id
        // 反推一级分类
        const top = topCategoryList.value.find(c => c.id === second.parentId)
        if (top) {
          topCategory.value = top.id
        }
      }
    }
  })
}*/
const showUpdateDialog = async (id) => {
  dialogFormVisible.value = true
  product.value = {}
  try {
    const result = await productApi.selectById(id)
    if (result.code !== 0) {
      ElMessage.error(result.msg || '获取商品失败')
      return
    }
    product.value = result.data
    console.log('loaded product:', product.value)

    // 保证 topCategoryList 已有数据（若没加载过就去拉一次）
    if (!topCategoryList.value || topCategoryList.value.length === 0) {
      const topRes = await categoryApi.selectTopCategoryList()
      if (topRes && topRes.data) topCategoryList.value = topRes.data
    }

    const targetCategoryId = product.value.categoryId // 二级分类id
    if (targetCategoryId) {
      // 遍历每个一级分类，拉取它的二级分类列表，找出包含 targetCategoryId 的那组
      for (const top of topCategoryList.value) {
        const secRes = await categoryApi.selectSecondCategoryListByParentId(top.id)
        const seconds = (secRes && secRes.data) ? secRes.data : []
        // 找到匹配的二级分类
        const match = seconds.find(c => String(c.id) === String(targetCategoryId))
        if (match) {
          topCategory.value = top.id           // 回显一级分类
          secondCategoryList.value = seconds  // 填充二级下拉数据
          product.value.categoryId = match.id // 回显二级（v-model）
          break
        }
      }
    } /*else {
      // 兜底：如果后端没有 categoryId，但返回了 top/second 名称，可以用名字去匹配
      if (product.value.topCategoryName) {
        const top = topCategoryList.value.find(c => c.name === product.value.topCategoryName)
        if (top) {
          topCategory.value = top.id
          const secRes = await categoryApi.selectSecondCategoryListByParentId(top.id)
          secondCategoryList.value = (secRes && secRes.data) ? secRes.data : []
          if (product.value.secondCategoryName) {
            const m = secondCategoryList.value.find(c => c.name === product.value.secondCategoryName)
            if (m) product.value.categoryId = m.id
          }
        }
      }
    }*/
  } catch (err) {
    console.error(err)
    ElMessage.error('加载商品或分类失败')
  }
}


const addOrUpdate = () => {
  if (product.value.id) {
    productApi.update(product.value).then(result => {
      if (result.code == 0) {
        ElMessage.success(result.msg)
        dialogFormVisible.value = false
        loadData()
      } else {
        ElMessage.error(result.msg)
      }
    })
  } else {
    productApi.add(product.value).then(result => {
      if (result.code == 0) {
        ElMessage.success(result.msg)
        dialogFormVisible.value = false
        loadData()
      } else {
        ElMessage.error(result.msg)
      }
    })
  }
}


//el-switch状态切换
const handleSwitchChange = (row) => {
  console.log(row)
  const product = {}
  product.id = row.id
  product.status = row.status
  productApi.update(product).then(result => {
    if (result.code == 0) {
      ElMessage.success(result.msg)
    } else {
      ElMessage.error(result.msg)
    }
  })
  /*productApi.updateStatus(row.id, row.status).then(result => {
      if (result.code == 0) {
          ElMessage.success(result.msg)
      } else {
          ElMessage.error(result.msg)
      }
  })*/
}

//图片上传
const handleAvatarSuccess = (result) => {
  product.value.mainImage = result.data
}

import {useTokenStore} from '@/store/token.js'

const tokenStore = useTokenStore();
const headers = ref({
  //携带token传递到后端
  Authorization: tokenStore.token
});

//富文本编辑器
const onEditorChange = (detail) => {
  product.value.detail = detail
}

//分类
const topCategory = ref()
const topCategoryList = ref([])
categoryApi.selectTopCategoryList().then(result => {
  topCategoryList.value = result.data
})

const secondCategoryList = ref([])
const selectChange = (value) => {
  product.value.categoryId = ''
  productQuery.value.categoryId = ''
  secondCategoryList.value = []
  if (value) {
    categoryApi.selectSecondCategoryListByParentId(value).then(result => {
      secondCategoryList.value = result.data
    })
  }
}

</script>

<template>
  <el-card class="">
    <template #header>
      <div class="header">
        <el-button type="primary" :icon="Plus" @click="showAddDialog">添加</el-button>
        <el-button type="primary" :icon="Delete" @click="deleteAll">批量删除</el-button>
        <el-button type="primary" :icon="Download" @click="exportExcel">导出Excel</el-button>
        <el-upload
            :icon="Upload"
            class="inline-block"
            multiple=""
            method="post"
            action="/api/course/importExcel"
            style="display:inline-block;margin-left: 12px"
            accept=".xlsx,.xls"
            :show-file-list="false"
            :on-success="importExcelSuccess"
            :headers="headers"
            name="file">
          <el-button type="primary" :icon="Upload">导入Excel</el-button>
        </el-upload>
      </div>
    </template>
    <el-form :inline="true">
      <el-form-item label="名字">
        <el-input v-model="productQuery.name" placeholder="请输入名字" clearable style="width: 200px"/>
      </el-form-item>
      <el-form-item label="分类" :label-width="60">
        <el-select v-model="topCategory" clearable placeholder="请选择一级分类" @change="selectChange"
                   style="width: 200px">
          <el-option
              v-for="category in topCategoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
          />
        </el-select>
        <el-select v-model="productQuery.categoryId" clearable placeholder="请选择二级分类" style="width: 200px">
          <el-option
              v-for="category in secondCategoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="更新时间" :label-width="80">
        <!--                <el-date-picker
                            v-model="productQuery.beginUpdateTime"
                            type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            placeholder="开始时间"
                        />
                        <el-date-picker
                            v-model="productQuery.endUpdateTime"
                            type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            placeholder="结束时间"
                        />-->
        <el-date-picker
            clearable
            v-model="dateTimeRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column fixed prop="id" label="ID"/>
      <el-table-column prop="name" label="名字"/>
      <el-table-column prop="topCategoryName" label="一级分类"/>
      <el-table-column prop="secondCategoryName" label="二级分类"/>
      <el-table-column prop="price" label="价格"/>
      <el-table-column prop="stock" label="库存"/>
      <el-table-column prop="status" label="是否禁用">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              :active-value="1"
              :inactive-value="0"
              active-text="正常"
              inactive-text="禁用"
              inline-prompt
              @change="handleSwitchChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="mainImage" label="主图">
        <template #default="{ row }">
          <img :src="row.mainImage" style="max-height: 40px; max-width: 120px;"/>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="avatar" label="头像"/> -->
      <el-table-column prop="updateTime" label="更新时间" width="180px"/>
      <el-table-column align="center" width="200px" fixed="right" label="操作">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="showUpdateDialog(row.id)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteById(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="productQuery.page"
        v-model:page-size="productQuery.limit"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @change="loadData"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>

  <!--添加、编辑弹出框-->
  <el-dialog v-model="dialogFormVisible" :title="title" width="70%" :lock-scroll="false">
    <el-form :model="product">
      <el-form-item label="名字" :label-width="60">
        <el-input v-model="product.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="子标题" :label-width="60">
        <el-input v-model="product.subtitle" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="分类" :label-width="60">
        <el-select v-model="topCategory" clearable placeholder="请选择一级分类" @change="selectChange"
                   style="width: 200px">
          <el-option
              v-for="category in topCategoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
          />
        </el-select>
        <el-select v-model="product.categoryId" clearable placeholder="请选择二级分类" style="width: 200px">
          <el-option
              v-for="category in secondCategoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="价格" :label-width="60">
        <el-input-number :min="0" v-model="product.price" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="库存" :label-width="60">
        <el-input-number :min="0" v-model="product.stock" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="主图" :label-width="60">
        <el-upload
            class="avatar-uploader"
            action="/api/product/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
        >
          <img v-if="product.mainImage" :src="product.mainImage" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <WangEditor :initValue="product.detail" @getEditorContent="onEditorChange"
                  v-if="dialogFormVisible" @close="dialogFormVisible = false"></WangEditor>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdate">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>